package com.chen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.domain.User;
import com.chen.domain.UserBank;
import com.chen.mapper.UserBankMapper;
import com.chen.service.UserBankService;
import com.chen.service.UserService;
import com.chen.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class UserBankServiceImpl extends ServiceImpl<UserBankMapper, UserBank> implements UserBankService {

    @Autowired
    private UserService userService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void bind(UserBank userBank) {
        List<UserBank> list = list(new LambdaQueryWrapper<UserBank>()
                .eq(UserBank::getUserId, UserUtil.getUser())
        );
        if(!CollectionUtils.isEmpty(list)){
            for (UserBank userBankUpdate : list){
                userBankUpdate.setStatus((byte)0);
            }
            updateBatchById(list);
        }

        User user = userService.getById(UserUtil.getUser());
        //交易密码是正确的
        String payPassword = userBank.getPayPassword();
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        if (!bCryptPasswordEncoder.matches(payPassword, user.getPaypassword())) {
            throw new IllegalArgumentException("交易密码不正确");
        }
        //todo 银行卡是正确的 --->  去阿里云上买一个身份证校验

        //添加用户银行卡信息
        userBank.setUserId(user.getId());
        userBank.setStatus((byte) 1);
        save(userBank);

    }
}
